﻿<?php
/**
* Stores Management
*/
class Admin_StoreController extends Zend_Controller_Action{	
	function init(){
            // System_Template::using('blank','Admin');
			System_Template::using('getit','Admin');
			
	     // Lấy các parameter trong request URL
            $this->Params = $this->getRequest()->getParams();            
            $this->view->maintitle = "Store Management";
            $this->model = new Admin_Model_Store();
			$this->storeCategoriesModel = new Admin_Model_StoreCategories();
			$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH.'/log.txt');
			$this->logger = new Zend_Log($writer);				
            parent::init();
	}
	
	/**
	* Index action
    */
	function indexAction(){
		//$this->view->maintitle = "Danh sách cửa hàng";		
		
		$storename = $this->_request->getParam("storename");
		$email = $this->_request->getParam("email");
		$storecategoryid = $this->_request->getParam("storecategoryid"); 
		$status = $this->_request->getParam("status");
		$higher = $this->_request->getParam("HIGHER");
		$lower = $this->_request->getParam("LOWER");
		
		$this->view->storename = $storename;
		$this->view->email = $email;
		$this->view->storecategoryid = $storecategoryid;
		$this->view->status = $status;
		$this->view->higher = $higher;
		$this->view->lower = $lower;
		$parameter = array('storename' => $storename, 'email' => $email, 'storecategoryid' => $storecategoryid,
				'status' => $status, "higher" => $higher, 'lower' => $lower);
		
		if(isset($this->Params['limit'])){
			$limit = (int) $this->Params['limit'];
		} else {
			$limit = 10;
		}
		if(isset($this->Params['page'])){
			$page = (int) $this->Params['page'];
		} else {
			$page = 1;
		}
		$numberOfItem = $this->model->count($parameter);
			
		$data = $this->model->SelectAll($parameter,$limit,($page-1)*$limit); 
		$this->view->data = $data;
		$this->view->limit = $limit;
		$this->view->page = $page;
		//Lấy danh sách store category ở đây để điền vào Combobox		
		$this->view->listStoreCategory = $this->storeCategoriesModel->SelectAllNoPaging();
		$this->view->pagination = common::pagination('/admin/store/index',$numberOfItem, 'right',$limit,$page);
	}
	/**
    * INVISIBLE
	* Input action
    */
	public function inputAction() {		
		//Dien thong tin tinh thanh quan huyen o day.	
		$this->view->listTinhThanh = $this->model->SelectAllCity();	
		$parentid=0;
		$storecategoryid=0;
		$id = $this->_request->getParam("id");
		if (!isset($id) || $id == 0 || $id == '') {
			$this->view->maintitle = "Add Store";
			//Lấy danh sách store category ở đây để điền vào Combobox
			$categoryParams = array('STATUS' => '1');
			$listCategories = $this->storeCategoriesModel->SelectAllByParentId(0);			
		} else {
			$this->view->maintitle = "Edit Store";
			$data = $this->model->FindById($id);
			$this->view->data = $data;
			$storecategoryid = $data['STORECATEGORYID'];
			//$parentid = $data['STORECATEGORYID'];
			//Lấy danh sách store category ở đây để điền vào Combobox
			$categoryParams = array('STATUS' => '1');
			$listCategories = $this->storeCategoriesModel->SelectAllByParentId($parentid);
			
			$this->view->logolnk = $this->model->GetMediaFilePath($id, 1);
			$this->view->image1lnk = $this->model->GetMediaFilePath($id, 2);
			$this->view->image2lnk = $this->model->GetMediaFilePath($id, 3);
			$this->view->image3lnk = $this->model->GetMediaFilePath($id, 4);
		}
		//Xử lý treeview ở đây.		
		$html = '';
		$this->getTreeView(&$html, $listCategories, $parentid, $storecategoryid, '');
		
		//getTreeView($html, $listCategories, $parentid, $storecategoryid);
        $this->view->htmlComboStorecategory = $html; 
	}
	
	/**
    * INVISIBLE
	* Upload action
    */
	public function uploadAction(){
		$this->_helper->layout->disableLayout();
		try{
			$uploader = new qqFileUploader(array(), ini_get('post_max_size'));
			$result = $uploader->handleUpload(PROJECT_HOME ."/upload/store/",true);
			$this->logger->info($result['success']);
		} catch (Zend_Exception $e){
			$this->logger->info($e->getMessage());
		}
		
		echo Zend_Json::encode($result);
		exit;
		/* $fileContents = file_get_contents($file);
		$sql ="insert into invoice(filelocation) values('$fileContents')"; */
	}

	/**
    * INVISIBLE
	* Save action
    */
	public function saveAction() {
		$this->Params = $this->getRequest()->getParams();
		$id = $this->Params['STOREID'];		
		
		if($id == 0 || $id == '')
		{
			$this->model->AddNewStore($this->Params);
			//Xử lý các link upload anh
			if($idstore > 0)
			{//Luu store thanh cong
			//logo
				$this->UpdateStoremedia(0, $this->Params['logofilename'],1, $idstore);
			//anh 1
				$this->UpdateStoremedia(0, $this->Params['image1filename'],2, $idstore);
			//anh 2
				$this->UpdateStoremedia(0, $this->Params['image2filename'],3, $idstore);
			//anh 3
				$this->UpdateStoremedia(0, $this->Params['image3filename'],4, $idstore);
			}
		}
		else
		{
			if($this->model->CheckExitsID($id))
			{
				$this->model->UpdateStore($this->Params);
				//Cap nhat duong dan anh
				//logo
				$this->UpdateStoremedia(1, $this->Params['logofilename'],1, $id);
				//anh 1
				$this->UpdateStoremedia(1, $this->Params['image1filename'],2, $id);
				//anh 2
				$this->UpdateStoremedia(1, $this->Params['image2filename'],3, $id);
				//anh 3
				$this->UpdateStoremedia(1, $this->Params['image3filename'],4, $id);
			}
			else
			{
				return "Error : STORE ID IS NOT EXISTS!";
			}
		}
		$this->logger->info($this->Params['NAME']);
		$this->_redirect('/admin/store/index');		
	}
	
	/**
	 * Update Store media
	 * $storemediaid : id of media. (0: add new, > 0 : update)
	 * 
	 **/
	public function UpdateStoremedia($storemediaid, $storemediaurl, $mediatype, $storeid )
	{
		$storeMediaModel = new Admin_Model_Storemedia();
		if($storemediaid <= 0)
		{//Insert
			$storemediadata = array('STOREMEDIAURL'=>$storemediaurl,'MEDIATYPE'=>$mediatype,'STOREID'=>$storeid);
			$storeMediaModel->addNew($storemediadata);
		}
		else
		{//Update			
			// $cond = array('MEDIATYPE'=>$mediatype,'STOREID'=>$storeid);
			// $strmedia = $storeMediaModel->SelectAll($cond);
			// foreach($strmedia as $row)
			// {
				// $storemediaid = $row['STOREMEDIAID'];
				// break;
			// }
			// if(isset($storemediaid) && $storemediaid > 0)
			// {
				$storemediadata = array('STOREMEDIAID'=>$storemediaid,'STOREMEDIAURL'=>$storemediaurl,'MEDIATYPE'=>$mediatype,'STOREID'=>$storeid);				
				$storeMediaModel->updateByMediatypeAndStoreid($storemediadata);
			// }
			// else
			// {
				// $storemediadata = array('STOREMEDIAURL'=>$storemediaurl,'MEDIATYPE'=>$mediatype,'STOREID'=>$storeid);
				// $storeMediaModel->addNew($storemediadata);
			// }
		}		
	}
	
	// // // /**
    // // // * INVISIBLE
	// // // * Select districts by cityid
    // // // */
	// // // public function deleteAction() {
		// // // $params = $this->getRequest()->getParams();
		// // // $db = Zend_Db_Table::getDefaultAdapter();
		// // // $ids = $params["DEL"];
		// // // for ($i = 0; $i < count($ids); $i++) {
			// // // $this->model->DeleteStore($ids[$i]);
		// // // }
		// // // $this->_redirect("/admin/store/index");
	// // // }
	
	/**
    * INVISIBLE
	* Select districts by cityid
    **/
	public function selectdistrictbycityidAction() {
		$cityid = $this->_request->getParam("cityid");		
		$districtid = $this->_request->getParam("districtid");   
		$r = $this->model->SelectAllDistrictOfCity($cityid);
		$html = '';
		foreach($r as $row) {
			if($districtid == $row['DISTRICTID']){
				$select = 'selected';
				$this->view->district = $row['NAME'];
			}
			else
				$select = '';
			$html .= '<option value="'. $row['DISTRICTID'] .'" '. $select .'>'. $row['NAME'] .'</option>';
		}
        echo $html;
        exit;
    }		
	
	/**
    * INVISIBLE
	* Get tree view of store categories
    */
	function getTreeView(&$html, $list, $parentid, $storecategoryid, $spaces){		
		$listChildren;
		//Lấy danh sách con theo id cha
		foreach($list as $row) {		
			if($parentid == $row['PARENTID'])
			{
				if($storecategoryid == $row['STORECATEGORYID']){
					$select = 'selected';
				}
				else{
					$select = '';
				}
				if($parentid == 0){
					$spaces = '';
				}
				else{
					$spaces.='--';
				}
				$html .= '<option value="'. $row['STORECATEGORYID'] .'" '. $select .'>'.$spaces.$row['NAME'] .'</option>';		
				//if(!isset($row['STORECATEGORYID']))
				//Lay ds listChildren
				$listChildren = $this->storeCategoriesModel->SelectAllByParentId($row['STORECATEGORYID']);
				//Add them cac node con
				$this->getTreeView(&$html, $listChildren, $row['STORECATEGORYID'], $storecategoryid, $spaces);
			}
		}
		//Kết thúc
	}
	
	/**
    * INVISIBLE
	* Change status of this Store
    */
    function changestatusAction() {
        $db = $this-> model -> getDefaultAdapter();
        $itemID = $this->Params['itemID'];
		$status = $this->Params['status'];
        $data = array('STATUS' => (int)$status);
        $rs = $db->update("store",$data, "STOREID = " . (int) $itemID);
        exit;
    }
	
	/**
    * INVISIBLE
	* Change status of multi stores
    */
    function changestatusmultiitemsAction(){
		$ids = $this -> Params['itemIDs'];
		$status = $this -> Params['status'];
		
        $db = $this -> model -> getDefaultAdapter();
        foreach($ids as $t){
            $this->logger->info($status);
			$data = array('STATUS' => (int)$status);
			$rs = $db->update("store",$data, "STOREID = " . (int) $t);
        }
	}
	
	/**
    * INVISIBLE
	* Change Store to featured or non-featured
    */
	function changefeaturedAction(){
		$db = $this-> model -> getDefaultAdapter();
        $itemID = $this->Params['itemID'];
		$status = $this->Params['featured'];
        $data = array('ISFEATURED' => (int)$status);
        $rs = $db->update("store",$data, "STOREID = " . (int) $itemID);
        exit;
	}
	
	/**
    * INVISIBLE
	* Change status of multi stores
    */
    function changefeaturedmultiitemsAction(){
		$ids = $this -> Params['itemIDs'];
		$status = $this -> Params['featured'];
		
        $db = $this -> model -> getDefaultAdapter();
        foreach($ids as $t){
            $data = array('ISFEATURED' => (int)$status);
			$rs = $db->update("store",$data, "STOREID = " . (int) $t);
        }
	}
	
	/**
    * INVISIBLE
	* Delete an User
    */
    function deleteAction() {
        $itemID = $this -> Params['id'];
		
		// Logging class initialization
        $db = $this -> model -> getDefaultAdapter();
        $db->delete("store","STOREID=".(int)$itemID);
        
        // Lưu lại phân trang trước
		if(!isset($this->Params['limit'])){
			$this->_redirect('/admin/store/index');
		} else {
			$this->_redirect('/admin/store/index/limit/'.$this->Params['limit']."/page/".$this->Params['page']);
		}
    }
	
	/**
    * INVISIBLE
	* Delete selected User
    */
	function deletemultiitemAction(){
		$ids = $this -> Params['ITEM'];
		$this->logger->info(sizeof($ids));
        $db = $this -> model -> getDefaultAdapter();
        foreach($ids as $t){
			
            $db->delete("store","STOREID=".(int)$t);
        }
        
        // Lưu lại phân trang trước
		if(!isset($this->Params['limit'])){
			$this->_redirect('/admin/store/index');
		} else {
			$this->_redirect('/admin/store/index/limit/'.$this->Params['limit']."/page/".$this->Params['page']);
		}
	}
	
	/**
    * INVISIBLE
	* Redirect to change owner email form
    */
	function changeownerAction(){
		$id = (isset($this->Params['itemID'])?$this->Params['itemID']:0);
		/* Trường hợp cập nhật */
		if($id>0){
			$data = $this->model->find($id)->current();
			$this->view->data = $data;
		} 
		$this->_helper->layout->disableLayout();
	}
	
	/**
    * INVISIBLE
	* Save new owner's email
    */
	function changeownersaveAction(){
		$id = (isset($this->Params['STOREID'])?$this->Params['STOREID']: '');
		$email = (isset($this->Params['EMAIL'])?$this->Params['EMAIL']: '');
		$db = Zend_Db_Table::getDefaultAdapter();
		try{
			$db->update('store', array('EMAIL' => $email),"STOREID = ".$id);;
			echo "successful";
		} catch(Zend_Exception $e) {
			echo $e->getMessage();
		}
		exit;
	}

}